import { Component, OnInit, ViewChild } from '@angular/core';
import { AxiosService } from '../../axios.service';
import { Router } from '@angular/router';
import { LocalStorageService } from 'src/app/myService/local-storage.service';
import { ActivatedRoute } from '@angular/router';
import { SubscribeService } from '../../myService/subscribe.service';



@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
  remark; // 职位（主管审核...）
  errmsg = '';
  // 保存登录状态
  isLogin = false;
  // 保存用户名
  public name: any;
  // 保存密码
  public password: any;
  public isChoose: Boolean = false;
  @ViewChild('errinfo', { static: false }) errinfo: any;
  // 申明HttpClient,ApiService服务
  constructor(
    public axios: AxiosService,
    private router: Router,
    private storage: LocalStorageService,
    public activatedRoute: ActivatedRoute,
    private subscribe: SubscribeService,
  ) {

    // SubscribeService
    this.activatedRoute.params.subscribe((data) => {
      if (data) {
        console.log("----------------------------\n", data)
        this.name = data.name;
      }
    })
  }

  ngOnInit(): void {

    if (this.storage.getStorageData('checked')) {
      this.isChoose = this.storage.getStorageData('checked');
    }

    if (this.isChoose) {
      if (this.storage.getStorageData('user')) {
        const userInfo = this.storage.getStorageData('user');
        this.name = userInfo.job_no;
        this.password = userInfo.password;
        console.log(this.name)
      }
    } else {
      if (this.storage.getStorageData('user')) {
        const userInfo = this.storage.getStorageData('user');
        this.name = userInfo.job_no;
      }
      this.password = '';
      // this.storage.removeStorageData('user');
    }

  }

  // 在自定义方法里请求数据
  saveUser() {
    if (!this.isChoose) {
      console.log(' 记住状态 \n', this.isChoose)
      this.storage.setStorageData('checked', true);
      // const userInfo: any = {};
      // userInfo.name = this.name;
      // userInfo.password = this.password;
      // this.storage.setStorageData('user',userInfo);
    } else {
      console.log(' 不  记住状态 \n', this.isChoose)
      this.storage.setStorageData('checked', false);
    }

  }
  doLogin() {
    this.axios.axiosPost('Login', { 'name': this.name, 'password': this.password })
      .then((data) => {
        console.log("------------------\n", data)

        // SubscribeService
        //  this.subscribe.sendLevel(data['level']);

        if (data['result'] === 'ok') {
          console.log(data)
          const userInfo: any = {};
          userInfo.name = data['name'];
          userInfo.name_PY = data['name_PY'];
          userInfo.job_no = data['job_no'];
          userInfo.department = data['department'];
          userInfo.department_abb = data['department_abb'];
          userInfo.role = data['role'];
          userInfo.level = data['level'];
          userInfo.password = this.password;
          userInfo.remark = data['remark'];
          this.storage.setStorageData('user', userInfo);

          if (data['role'] === '管理員' || '用戶' || '客戶') {
            const level = data['level'].toString(2);
            const levelArr = [];
            const levelData = [];
            for (let i = 0; i < level.length; i++) {
              levelArr.push(level[i]);
            }
            for (let i = 0; i < levelArr.length; i++) {
              if (levelArr.length < 16) {
                levelArr.unshift('0');
              }
              if (levelArr[i] === '0') {
                levelData.push(false);
              } else {
                levelData.push(true);
              }
            }
            console.log(level);
            console.log(levelArr);
            console.log(levelData);
            // // 查找符合item条件的下标
            let index = levelData.findIndex((item) => {
              return item === true;
            })
            console.log(index)
            let routerArr = ['audit', 'empDesign', 'empProgram', 'empProcess', 'empZhijian', 'empJiagong', 'empZuzhuang', 'empZongjian', 'ruku', 'paijian', 'empKufang', 'lingliao','kanbanManage','baobiao','paiban', 'permissions'];
            console.log('home/' + routerArr[12])
            this.router.navigate(['home/' + routerArr[index]]);
          }
        } else {
          if (data['errorCode'] === '1') {
            this.errmsg = '用戶名不存在';
          }
          if (data['errorCode'] === '2') {
            this.errmsg = '密碼錯誤';
          }
        }
      })
      .catch((err) => {
        console.log(err);
        // if(this.name!='Guo yang' || this.password!='123456q'){
        //   this.errmsg='用戶名或密碼錯誤！'
        //   this.errinfo.nativeElement.style.display = 'inline';
        // }else if(this.name==='' || this.password===''){
        //   this.errmsg='用戶名或密碼不能为空！'
        //   this.errinfo.nativeElement.style.display = 'inline';
        // }
      })

  }

}
